package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerLinearViewItemDecoration;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.DianZanObject;
import com.lishe.base.common.config.Constants;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.adapter.CommentAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.CommentObject;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendCommentDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendGiftDialog;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnMessageChangeListener;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.module.excitation.presenter.MinePresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.lishe.widget.CircleImageView;
import com.lishe.lishe.lishe.widget.RoundImageView;
import com.lishe.lishe.retrofit.BaseDataPageBody;
import com.lishe.lishe.retrofit.BaseRequestBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.LinkedList;

/**
 * Created by shino on 2017/10/22.
 * 点赞详情
 */

public class DianZanDetailsActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = DianZanDetailsActivity.class.getSimpleName();

    private Button callBack;
    private TextView title;
    private CircleImageView headImage;
    private ImageView lable, heart;
    private RoundImageView[] images = new RoundImageView[3];
    //    private ImageView image2;
//    private ImageView image3;
    private TextView name;
    private TextView occupation;
    private TextView note;
    private TextView company;
    private TextView content;
    private TextView time;
    private TextView commentCount;
    private LinearLayout forwardLayout;
    private TextView forwar;
    private LinearLayout commentLayout;
    private TextView comment;
    private LinearLayout giftLayout;
    private TextView gift;
    private LinearLayout dianzanLayout, imageLayout;
    private TextView dianzan;
    private RecyclerView listView;
    private TextView empty;
//    private TextView empty_text;
    private SmartRefreshLayout mSmartRefreshLayout;

    private CommentAdapter adapter;
    private LinkedList<CommentObject> commentObjects = new LinkedList<>();
    private static DianZanObject mDianZanObject;
    private int page = 1, pageSize = 20, totalPage;
    private boolean isDianzan = true;
    private String mDianZanId;
    private String messageId;
    private boolean isNotify = false;//消息阅读通知

    public static void jump(Fragment fragment, DianZanObject dianZanObject, int requestCode) {
        Intent intent = new Intent(fragment.getActivity(), DianZanDetailsActivity.class);
        mDianZanObject = dianZanObject;
        intent.putExtra("dianZanObject", dianZanObject);
        fragment.startActivityForResult(intent, requestCode);
    }

    public static void jump(Fragment fragment, String dianZanId, String messageId, int requestCode, boolean isNotify) {
        Intent intent = new Intent(fragment.getActivity(), DianZanDetailsActivity.class);
        mDianZanObject = null;
        intent.putExtra("dianZanId", dianZanId);
        intent.putExtra("messageId", messageId);
        intent.putExtra("isNotify", isNotify);
        fragment.startActivityForResult(intent, requestCode);
    }

    public static void jump(Activity activity, DianZanObject dianZanObject, int requestCode) {
        Intent intent = new Intent(activity, DianZanDetailsActivity.class);
        mDianZanObject = dianZanObject;
        intent.putExtra("dianZanObject", dianZanObject);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dianzan_details);
        mDianZanId = getIntent().getStringExtra("dianZanId");
        messageId = getIntent().getStringExtra("messageId");
        isNotify = getIntent().getBooleanExtra("isNotify", false);
        initView();
        initAdapter();
        //添加RecycleView 头布局
        addHeaderView();
        //设置刷新控件
        setSmartRefreshLayout();
        setListener();
        if (mDianZanId == null) {
            Log.e("mDianZanId", "null");
        }
        if (mDianZanObject == null) {
            if (mDianZanId != null) {
                getDianZanDEtial();
            }
        } else {
            updateDianZanDetail();
        }
        if (isNotify) {
            upMessageStatus(messageId);
        }

    }

    private void initView() {
        callBack = findViewById(R.id.title_left_button);
        title = findViewById(R.id.title_text_title);

        forwardLayout = findViewById(R.id.forward_layout);
        forwar = findViewById(R.id.forward);
        commentLayout = findViewById(R.id.comment_layout);
        comment = findViewById(R.id.comment);
        giftLayout = findViewById(R.id.gift_layout);
        gift = findViewById(R.id.gift);
        dianzanLayout = findViewById(R.id.dianzan_layout);
        dianzan = findViewById(R.id.dianzan);
        listView = findViewById(R.id.listView);
        heart = findViewById(R.id.heart);
        mSmartRefreshLayout = findViewById(R.id.refreshlayout);

        title.setText("点赞详情");
    }

    private void updateDianZanDetail() {
//        new ImageLoaderUtils().displayImage(mDianZanObject.getAvatarPath(), headImage);
        ImageLoaderUtils.displayImage(DianZanDetailsActivity.this, mDianZanObject.getAvatarPath(), headImage,R.mipmap.head);
        name.setText(mDianZanObject.getEmpName());
        occupation.setText(TextUtils.isEmpty(mDianZanObject.getPosName()) ? "" : mDianZanObject.getPosName());
        company.setText(mDianZanObject.getCreateUserName());
        content.setText(StringUtils.utf8ToString(mDianZanObject.getEventDesc()));
        note.setText(mDianZanObject.getActionName());
        time.setText(mDianZanObject.getCreateTime());

        if (mDianZanObject.getCreateUserType().equals("0")) {
            lable.setVisibility(View.VISIBLE);
        } else {
            lable.setVisibility(View.GONE);
        }

        if (mDianZanObject.getImgList() == null || mDianZanObject.getImgList().size() == 0) {
            imageLayout.setVisibility(View.GONE);
        }

        if (mDianZanObject.getImgList().size() == 1) {
            images[1].setVisibility(View.INVISIBLE);
            images[2].setVisibility(View.INVISIBLE);
        }
        for (int i = 0; i < mDianZanObject.getImgList().size(); i++) {
            images[i].setVisibility(View.VISIBLE);
            images[i].setTag(mDianZanObject.getImgList().get(i).getImgUrl());
            ImageLoaderUtils.setImageResource(this, mDianZanObject.getImgList().get(i).getImgUrl(), images[i], R.drawable.defalut_img);
        }

        updateNumber();

    }

    private void addHeaderView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_dianzan_detail_header, null);
        headImage = headerView.findViewById(R.id.head_img);
        lable = headerView.findViewById(R.id.lable);
        images[0] = headerView.findViewById(R.id.image1);
        images[1] = headerView.findViewById(R.id.image2);
        images[2] = headerView.findViewById(R.id.image3);
        name = headerView.findViewById(R.id.name);
        occupation = headerView.findViewById(R.id.occupation);
        note = headerView.findViewById(R.id.note);
        company = headerView.findViewById(R.id.company);
        content = headerView.findViewById(R.id.content);
        time = headerView.findViewById(R.id.time);
        commentCount = headerView.findViewById(R.id.comment_count);
        imageLayout = headerView.findViewById(R.id.image_layout);
        empty = headerView.findViewById(R.id.empty);
//        empty_text = headerView.findViewById(R.id.empty_text);

        int displayWidth= BitmapUtils.getDisplayWidth(this);
        int width=(displayWidth-Utils.dip2px(context,40))/3;
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(width,width);
        LinearLayout.MarginLayoutParams params1=params;
        params1.rightMargin=Utils.dip2px(context,5);
        images[0].setLayoutParams(params1);
        images[1].setLayoutParams(params1);
        images[2].setLayoutParams(params1);

        adapter.addHeaderView(headerView);
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getCommetnList();
                mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                if(!mSmartRefreshLayout.isEnableLoadmore()) mSmartRefreshLayout.setEnableLoadmore(true);
            }
        });

        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //未加载完，可以LoadMore
                if (page <= totalPage) {
                    mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                    getCommetnList();
                } else {
                    mSmartRefreshLayout.finishLoadmore();
                    mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                }

            }
        });
    }

    private void updateNumber() {
        forwar.setText(mDianZanObject.getShareCount() > 0 ? String.valueOf(mDianZanObject.getShareCount()) : "转发");
        gift.setText(mDianZanObject.getGiftCount() > 0 ? String.valueOf(mDianZanObject.getGiftCount()) : "礼物");
        comment.setText(mDianZanObject.getCommentCount() > 0 ? String.valueOf(mDianZanObject.getCommentCount()) : "评论");
        commentCount.setText(mDianZanObject.getCommentCount() > 0 ? "评论(" + mDianZanObject.getCommentCount() + ")" : "评论");
        dianzan.setText(mDianZanObject.getAdmiredCount() > 0 ? String.valueOf(mDianZanObject.getAdmiredCount()) : "鼓励");

        if (mDianZanObject.isFlag()) {
            heart.setImageResource(R.mipmap.heart_red);
            dianzan.setTextColor(getResources().getColor(R.color.color_ff4138));
        } else {
            heart.setImageResource(R.mipmap.heart_black);
            dianzan.setTextColor(getResources().getColor(R.color.color_999999));
        }
    }

    private void setListener() {
        callBack.setOnClickListener(this);
        images[0].setOnClickListener(this);
        images[1].setOnClickListener(this);
        images[2].setOnClickListener(this);
        forwardLayout.setOnClickListener(this);
        commentLayout.setOnClickListener(this);
        giftLayout.setOnClickListener(this);
        dianzanLayout.setOnClickListener(this);
        headImage.setOnClickListener(this);
        name.setOnClickListener(this);
        company.setOnClickListener(this);
    }

    private void initAdapter() {
        listView.setLayoutManager(new LinearLayoutManager(DianZanDetailsActivity.this));
        listView.addItemDecoration(new RecyclerLinearViewItemDecoration(Utils.dip2px(DianZanDetailsActivity.this, 15), false));
        adapter = new CommentAdapter(DianZanDetailsActivity.this, commentObjects);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == DianzanShareActivity.requestCode) {
            if (resultCode == RESULT_OK) {
                mDianZanObject.setShareCount(mDianZanObject.getShareCount() + 1);
                updateNumber();
            }
        }
    }

    @Override
    public void onBackPressed() {
        onBack();
    }

    private void onBack() {
        setResult(RESULT_OK, null);
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.company:
                if (mDianZanObject == null) {
                    break;
                }
                if (!mDianZanObject.getCreateUserType().equals("0")) {
                    //点击头像跳转个人中心
                    PersonExcitationActivity.jump(DianZanDetailsActivity.this, mDianZanObject.getCreateUserId());
                }
                break;
            case R.id.name:
            case R.id.head_img:
                if (mDianZanObject == null) {
                    break;
                }
                //点击头像跳转个人中心
                PersonExcitationActivity.jump(DianZanDetailsActivity.this, mDianZanObject.getUserId());
                break;
            case R.id.title_left_button:
                onBack();
                break;
            case R.id.image1:
                if (mDianZanObject == null) {
                    break;
                }
                if (mDianZanObject.getImgList().size() > 0)
                    showFullScreenDialog(0);
                break;
            case R.id.image2:
                if (mDianZanObject == null) {
                    break;
                }
                if (mDianZanObject.getImgList().size() > 1)
                    showFullScreenDialog(1);
                break;
            case R.id.image3:
                if (mDianZanObject == null) {
                    break;
                }
                if (mDianZanObject.getImgList().size() > 2)
                    showFullScreenDialog(2);
                break;
            case R.id.forward_layout:
                if (mDianZanObject == null) {
                    break;
                }
                DianzanShareActivity.jump(DianZanDetailsActivity.this, mDianZanObject.getEventId(), mDianZanObject.getAvatarPath(), mDianZanObject.getEmpName(), mDianZanObject.getEventDesc());
                break;
            case R.id.gift_layout:
                if (mDianZanObject == null) {
                    break;
                }
                if (mDianZanObject.getUserId().equals(Globals.getExcatationUserId())) {
                    PersonReceiveGiftActivity.jump(DianZanDetailsActivity.this, mDianZanObject.getEventId());
                } else {
                    ShowSendGiftDialog.Builder builder = new ShowSendGiftDialog.Builder(DianZanDetailsActivity.this);
                    builder.setEventId(mDianZanObject.getEventId())
                            .setEventUserId(mDianZanObject.getUserId())
                            .setPointsType(1)
                            .setOnMessageChangeListener(listener);
                    builder.show();
                }
                break;
            case R.id.comment_layout:
                if (mDianZanObject == null) {
                    break;
                }
                ShowSendCommentDialog.Builder builder2 = new ShowSendCommentDialog.Builder(DianZanDetailsActivity.this);
                builder2.setEventId(mDianZanObject.getEventId())
                        .setOnMessageChangeListener(listener);
                builder2.show();
                break;
            case R.id.dianzan_layout:
                if (mDianZanObject == null) {
                    break;
                }

                if (mDianZanObject.getUserId().equals(Globals.getExcatationUserId())) {
                    //跳转到鼓励列表
                    PersonReceiveAdmireActivity.jump(DianZanDetailsActivity.this, mDianZanObject.getEventId());
                } else {
                    if (mDianZanObject.isFlag()) {
                        cancelHitEvent();
                    } else {
                        dianZanEvent();
                    }
                }
                break;
        }
    }

    private void showFullScreenDialog(int position) {
        startActivity(new Intent(this, PictureViewerActivity.class)
                .putExtra(Constants.PICTURE_VIEWER_POSITION, position).putExtra(Constants.PICTURE_VIEWER_IMAGES, mDianZanObject.getImgList()));
    }

    private OnMessageChangeListener listener = new OnMessageChangeListener() {
        @Override
        public void messageChange(int type, int changeNum) {
            if (type == OnMessageChangeListener.GIFT_CHANGE_SUCCESS) {
                mDianZanObject.setGiftCount(mDianZanObject.getGiftCount() + changeNum);
                gift.setText(String.valueOf(mDianZanObject.getGiftCount()));
            } else if (type == OnMessageChangeListener.COMMENT_CHANGE_SUCCESS) {
                if (commentObjects.size() > 0) {
                    listView.scrollToPosition(0);
                }
                mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
                mDianZanObject.setCommentCount(mDianZanObject.getCommentCount() + changeNum);
            }
            updateNumber();
        }
    };

    /**
     * 获取点赞详情
     */
    private void getDianZanDEtial() {
        try {
            if (mDianZanId != null) {
                MinePresenter.getInstance().getEventDetail(Globals.getToken(), mDianZanId, dianzanDetailListener);
            } else {
                MinePresenter.getInstance().getEventDetail(Globals.getToken(), mDianZanObject.getEventId(), dianzanDetailListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private DataResponseListener<DianZanObject> dianzanDetailListener = new DataResponseListener<DianZanObject>() {

        @Override
        public void onPrepare() {
            super.onPrepare();
            LoadingUtils.createLoadingDialog(DianZanDetailsActivity.this, getString(R.string.loading), true);
        }

        @Override
        public void onSuccess(DianZanObject dataResponse) {
            LoadingUtils.closeDialog();
            mDianZanObject = dataResponse;
            updateDianZanDetail();
        }

        @Override
        public void onFail(String failMessage) {
            LoadingUtils.closeDialog();
            toast(failMessage);
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            LoadingUtils.closeDialog();
            toast(R.string.network_or_server_exception);
        }
    };

    /**
     * 获取评论列表
     */
    private void getCommetnList() {
        try {
            if (mDianZanId != null) {
                MinePresenter.getInstance().getEventCommentList(Globals.getToken(), mDianZanId, String.valueOf(page), String.valueOf(pageSize), commentListener);
            } else {
                MinePresenter.getInstance().getEventCommentList(Globals.getToken(), mDianZanObject.getEventId(), String.valueOf(page), String.valueOf(pageSize), commentListener);
            }
        } catch (Exception e) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            if (commentObjects.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将会再次触发加载更多事件
            }
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private DataResponseListener<BaseDataPageBody<CommentObject>> commentListener = new DataResponseListener<BaseDataPageBody<CommentObject>>() {
        @Override
        public void onPrepare() {
            super.onPrepare();

        }

        @Override
        public void onSuccess(BaseDataPageBody<CommentObject> dataResponse) {
            if (page == 1) {
                mSmartRefreshLayout.finishRefresh(500, true);
                commentObjects.clear();
            } else {
                mSmartRefreshLayout.finishLoadmore(500, true);
            }
            page++;
            totalPage = dataResponse.getTotalPage();
            commentObjects.addAll(dataResponse.getInfo());



            if (commentObjects.size() > 0) {
                empty.setVisibility(View.GONE);
                adapter.notifyDataSetChanged();
            } else {
                empty.setVisibility(View.VISIBLE);
//                empty_text.setText(R.string.no_comment);
                mSmartRefreshLayout.setEnableLoadmore(false);
            }

        }

        @Override
        public void onFail(String failMessage) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            toast(failMessage);
            if (commentObjects.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
//                empty_text.setText(R.string.no_comment);
                empty.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onError(Throwable e) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            e.printStackTrace();
            toast(R.string.network_or_server_exception);
            if (commentObjects.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
//                empty_text.setText(R.string.network_or_server_exception);
                empty.setVisibility(View.VISIBLE);
            }
        }
    };

    /**
     * 点赞事件
     */
    private void dianZanEvent() {
        try {
            if (mDianZanId != null) {
                MinePresenter.getInstance().hitEvent(Globals.getToken(), mDianZanId, hitEventListener);
            } else {
                MinePresenter.getInstance().hitEvent(Globals.getToken(), mDianZanObject.getEventId(), hitEventListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private DataResponseListener hitEventListener = new DataResponseListener() {
        @Override
        public void onSuccess(Object dataResponse) {
            if (mDianZanObject.isFlag()) {
//                        toast("取消点赞");
                mDianZanObject.setFlag(false);
                mDianZanObject.setAdmiredCount(mDianZanObject.getAdmiredCount() - 1);
            } else {
//                        toast("点赞成功");
                mDianZanObject.setFlag(true);
                mDianZanObject.setAdmiredCount(mDianZanObject.getAdmiredCount() + 1);
            }

            updateNumber();
        }

        @Override
        public void onFail(String failMessage) {
            toast(failMessage);
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            toast(R.string.network_or_server_exception);
        }
    };

    /**
     * 取消点赞事件
     */
    private void cancelHitEvent() {
        try {
            if (mDianZanId != null) {
                MinePresenter.getInstance().cancelHitEvent(Globals.getToken(), mDianZanId, hitEventListener);
            } else {
                MinePresenter.getInstance().cancelHitEvent(Globals.getToken(), mDianZanObject.getEventId(), hitEventListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private void upMessageStatus(String id) {
        ExcitationPresenter.getInstance().updateNewsStatus(id, Globals.getToken(), new DataResponseListener<BaseRequestBody>() {
            @Override
            public void onSuccess(BaseRequestBody dataResponse) {

            }

            @Override
            public void onFail(String failMessage) {

            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }
}
